<template>
  <div class="statistics-dashboard">
    <!-- 统计卡片 -->
    <el-row :gutter="20" v-if="$route.path === '/admin/statistics'">
      <el-col :span="6" v-for="(card, index) in statCards" :key="index">
        <el-card 
          shadow="hover" 
          class="stat-card" 
          @click="handleCardClick(card.path)"
        >
          <div class="stat-icon">
            <el-icon>
              <component :is="card.icon" />
            </el-icon>
          </div>
          <div class="stat-info">
            <h3>{{ card.title }}</h3>
            <p>{{ card.description }}</p>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 仪表盘内容，只在主统计页面显示 -->
    <template v-if="$route.path === '/admin/statistics'">
      <el-row :gutter="20" class="chart-row">
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>平台概览</span>
                <el-radio-group v-model="overviewType" size="small" @change="handleOverviewTypeChange">
                  <el-radio-button label="daily">日</el-radio-button>
                  <el-radio-button label="weekly">周</el-radio-button>
                  <el-radio-button label="monthly">月</el-radio-button>
                </el-radio-group>
              </div>
            </template>
            <div class="chart-container">
              <v-chart :option="overviewOption" autoresize />
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>用户活跃度</span>
                <el-select v-model="activityMetric" style="width: 120px">
                  <el-option label="访问量" value="visits" />
                  <el-option label="互动数" value="interactions" />
                  <el-option label="转化率" value="conversion" />
                </el-select>
              </div>
            </template>
            <div class="chart-container">
              <v-chart :option="activityOption" autoresize />
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-card class="quick-stats">
        <template #header>
          <div class="card-header">
            <span>实时数据</span>
            <el-button type="primary" link @click="refreshRealTimeData">
              <el-icon><Refresh /></el-icon> 刷新
            </el-button>
          </div>
        </template>
        <el-table :data="realTimeData" stripe style="width: 100%">
          <el-table-column prop="time" label="时间" width="180" />
          <el-table-column prop="activeUsers" label="在线用户" width="120" />
          <el-table-column prop="pageViews" label="页面浏览" width="120" />
          <el-table-column prop="orders" label="订单数" width="120" />
          <el-table-column prop="sales" label="销售额">
            <template #default="{ row }">
              ¥{{ formatNumber(row.sales) }}
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </template>

    <!-- 子路由内容 -->
    <router-view v-else />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Shop,
  User,
  ChatDotSquare,
  ShoppingCart,
  Refresh
} from '@element-plus/icons-vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'

// 注册必需的组件
use([
  CanvasRenderer,
  LineChart,
  BarChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

const router = useRouter()

// 统计卡片数据
const statCards = [
  {
    title: '商品统计',
    description: '商品销售、库存、转化率分析',
    icon: 'ShoppingCart',
    path: 'product'
  },
  {
    title: '用户统计',
    description: '用户行为、画像、活跃度分析',
    icon: 'User',
    path: 'user'
  },
  {
    title: '评论统计',
    description: '评论数据、情感分析、关键词',
    icon: 'ChatDotSquare',
    path: 'comment'
  },
  {
    title: '商家统计',
    description: '商家销售、订单、评分分析',
    icon: 'Shop',
    path: 'merchant'
  }
]

// 数据定义
const overviewType = ref('daily')
const activityMetric = ref('visits')
const realTimeData = ref([])
let realTimeTimer = null

// 平台概览图表配置
const overviewOption = computed(() => ({
  title: {
    text: '平台数据概览'
  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['访问量', '订单量', '销售额']
  },
  xAxis: {
    type: 'category',
    data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  },
  yAxis: [
    {
      type: 'value',
      name: '数量',
      position: 'left'
    },
    {
      type: 'value',
      name: '金额',
      position: 'right',
      axisLabel: {
        formatter: '¥{value}'
      }
    }
  ],
  series: [
    {
      name: '访问量',
      type: 'bar',
      data: [820, 932, 901, 934, 1290, 1330, 1320]
    },
    {
      name: '订单量',
      type: 'bar',
      data: [320, 332, 301, 334, 390, 330, 320]
    },
    {
      name: '销售额',
      type: 'line',
      yAxisIndex: 1,
      data: [2200, 2900, 2100, 2600, 3200, 3100, 2900]
    }
  ]
}))

// 用户活跃度图表配置
const activityOption = computed(() => ({
  title: {
    text: '用户活跃度分析'
  },
  tooltip: {
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    data: ['00:00', '04:00', '08:00', '12:00', '16:00', '20:00', '23:59']
  },
  yAxis: {
    type: 'value',
    name: activityMetric.value === 'conversion' ? '转化率' : '数量',
    axisLabel: {
      formatter: activityMetric.value === 'conversion' ? '{value}%' : '{value}'
    }
  },
  series: [
    {
      data: activityMetric.value === 'conversion'
        ? [3.2, 2.8, 4.5, 7.8, 8.2, 6.5, 4.2]
        : [120, 200, 450, 780, 820, 650, 420],
      type: 'line',
      smooth: true,
      areaStyle: {
        opacity: 0.3
      }
    }
  ]
}))

// 处理概览类型变化
const handleOverviewTypeChange = () => {
  // 根据选择的时间维度更新数据
  // 这里应该调用后端API获取相应的数据
}

// 格式化数字
const formatNumber = (num) => {
  if (!num) return '0'
  return num.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

// 刷新实时数据
const refreshRealTimeData = () => {
  // 模拟实时数据
  realTimeData.value = [
    {
      time: new Date().toLocaleString(),
      activeUsers: Math.floor(Math.random() * 1000),
      pageViews: Math.floor(Math.random() * 5000),
      orders: Math.floor(Math.random() * 100),
      sales: Math.floor(Math.random() * 100000)
    },
    // ... 可以添加更多数据
  ]
}

// 启动实时数据更新
const startRealTimeUpdate = () => {
  refreshRealTimeData()
  realTimeTimer = setInterval(refreshRealTimeData, 60000) // 每分钟更新一次
}

// 组件挂载时启动实时更新
onMounted(() => {
  startRealTimeUpdate()
})

// 组件卸载时清理定时器
onUnmounted(() => {
  if (realTimeTimer) {
    clearInterval(realTimeTimer)
  }
})

// 处理卡片点击
const handleCardClick = (path) => {
  router.push(`/admin/statistics/${path}`)
}
</script>

<style scoped>
.statistics-dashboard {
  padding: 20px;
}

.card-link {
  text-decoration: none;
  color: inherit;
  display: block;
  margin-bottom: 20px;
}

.stat-card {
  height: 160px;
  transition: transform 0.3s;
  cursor: pointer;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-icon {
  font-size: 48px;
  color: #409EFF;
  margin-bottom: 16px;
}

.stat-info h3 {
  margin: 0 0 8px;
  font-size: 18px;
}

.stat-info p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-container {
  height: 400px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.quick-stats {
  margin-bottom: 20px;
}

:deep(.el-card__header) {
  padding: 15px 20px;
}
</style> 